import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { Role } from '../modules/role/entities/role.entity';
import { User } from '../modules/user/entities/user.entity';
import { InitAdminCommand } from './init-admin.command';
import { createDatabaseConfig } from '../config/database.config';
import * as yaml from 'js-yaml';
import * as fs from 'fs';
import * as path from 'path';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [() => {
        // 支持通过环境变量指定环境，默认为 development
        const env = process.env.NODE_ENV || 'development';
        
        // 映射环境名称到配置文件名
        const envMap = {
          'development': 'dev',
          'production': 'prod',
          'test': 'test'
        };
        const configFile = envMap[env] || 'dev';
        
        // 读取主配置文件
        const mainConfig = yaml.load(
          fs.readFileSync(path.join(process.cwd(), 'config', 'application.yml'), 'utf8'),
        );
        
        // 读取环境特定配置文件
        const envConfig = yaml.load(
          fs.readFileSync(path.join(process.cwd(), 'config', `application-${configFile}.yml`), 'utf8'),
        );
        
        // 合并配置
        const config = deepMerge(mainConfig, envConfig);
        
        // 支持通过环境变量覆盖敏感配置
        if (process.env.DB_HOST) config.database.host = process.env.DB_HOST;
        if (process.env.DB_PORT) config.database.port = parseInt(process.env.DB_PORT);
        if (process.env.DB_USERNAME) config.database.username = process.env.DB_USERNAME;
        if (process.env.DB_PASSWORD) config.database.password = process.env.DB_PASSWORD;
        if (process.env.DB_DATABASE) config.database.database = process.env.DB_DATABASE;
        
        return config;
      }],
    }),
    TypeOrmModule.forRootAsync({
      useFactory: (configService) => createDatabaseConfig(configService),
      inject: [ConfigService],
    }),
    TypeOrmModule.forFeature([Role, User]),
  ],
  providers: [InitAdminCommand],
})
export class CliModule {}

// 深度合并对象
function deepMerge(target: any, source: any): any {
  const result = { ...target };
  
  for (const key in source) {
    if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
      result[key] = deepMerge(result[key] || {}, source[key]);
    } else {
      result[key] = source[key];
    }
  }
  
  return result;
}